package com.hns.can.service.web;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.service.service.DriverCommentService;
import com.hns.can.service.service.DriverEmotionalService;
import com.hns.can.service.service.DriverExamService;
import com.hns.can.service.vo.DriverCommentParamsVo;
import com.hns.can.service.vo.DriverEmotionalVo;
import com.hns.can.service.vo.EnergyVo;
import com.hns.can.common.domain.GridPage;
import com.hns.can.common.web.BaseController;
import com.hns.frame.mybatis.Pagination;
import com.hns.tool.export.ExportUtil;
import com.hns.tool.pub.DateTool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 驾驶心情指数controller
 * @author:zhangzq
 * @email:
 * @version Revision 2.0.0
 */
@Controller
@RequestMapping("/driverEmotional")
public class DriverEmotionalController extends BaseController {

    @Autowired
    private DriverExamService driverExamService;
    @Autowired
    DriverEmotionalService driverEmotionalService;
    @Autowired
    DriverCommentService driverCommentService;

    final private String[] headerNames = { "排名", "得分","驾驶员", "营运线路", "所属机构", "运行时长", "运行里程(KM)", "异常次数", "惯性异常", "心情急躁", "超车未果"};
    final private String[] headerFields = { "allrank", "score","drvName", "lineName", "organName", "totalOprtDura", "totalMile", "sumabnormal", "cntIeta", "cntImpati", "cntOvertake"};

    /**
     * 获取情绪数据用于导出
     *
     * @param vo
     * @throws Exception
     * @author:zhangzq
     * @email:
     */
    private List<DriverEmotionalVo> getSecurityGradeInfo(EnergyVo vo) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        driverExamService.initParams(vo, user, "T_COMM_DRV_SCT_BHV_INFO");
        driverExamService.getReportDate(vo.getBeginTime(), vo.getReportType(), vo);
        List<DriverEmotionalVo> list = driverEmotionalService.exportDriverEmotional(vo);
        return list;
    }

    /**
     * 分页查询情绪数据
     *
     * @param vo
     * @throws Exception
     * @author:zhangzq
     * @email:
     */
    @RequestMapping("/searchDriverEmotional")
    @ResponseBody
    public Object searchAbnormalInquiry(EnergyVo vo) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        driverExamService.initParams(vo, user, Arrays.asList("T_COMM_ENER_CONS_STAT_INFO", "T_COMM_DRIVE_MD_IDNX_INFO"));
        driverExamService.getReportDate(vo.getBeginTime(), vo.getReportType(), vo);
        Pagination page = driverEmotionalService.searchDriverEmotional(vo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }

    /**
     * 导出情绪数据Excel文档
     *
     * @param vo
     * @throws Exception
     * @author:zhangzq
     * @email:
     */
    @RequestMapping("/exportDriverEmotionalExcel")
    public void exportAbnormalInquiryExcel(EnergyVo vo, HttpServletResponse response) throws Exception {
        List<DriverEmotionalVo> list = getSecurityGradeInfo(vo);
        ExportUtil.exportFiles(Arrays.asList(headerNames), Arrays.asList(headerFields), list, response, "excel", URLEncoder.encode("驾驶员情绪考核", "UTF-8") + DateTool.getCurrentSysDate("yyyyMMddHHmmss"), "驾驶员情绪数据");
    }

    /**
     * 导出情绪数据Pdf文档
     *
     * @param vo
     * @throws Exception
     * @author:zhangzq
     * @email:
     */
    @RequestMapping("/exportDriverEmotionalPdf")
    public void exportAbnormalInquiryPdf(EnergyVo vo, HttpServletResponse response) throws Exception {
        List<DriverEmotionalVo> list = getSecurityGradeInfo(vo);
        ExportUtil.exportFiles(Arrays.asList(headerNames), Arrays.asList(headerFields), list, response, "pdf", URLEncoder.encode("驾驶员情绪考核", "UTF-8") + DateTool.getCurrentSysDate("yyyyMMddHHmmss"), "驾驶员情绪数据");
    }

    /**
     * 情绪数据
     *
     * @param vo
     * @throws Exception
     * @author:zhangzq
     * @email:
     */
    @RequestMapping("/searchDrvEmotionalInfo")
    @ResponseBody
    public Object searchDrvEmotionalInfo(EnergyVo vo) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        vo.setCorpId(user.getCorpId());
        List<DriverEmotionalVo> list = driverEmotionalService.searchDrvEmotionalInfo(vo);
        int sumAbnormal=0;
        String  moodOccurTime = vo.getBeginTime();
        Calendar lastDate1 = Calendar.getInstance();
        Calendar lastDate2 = Calendar.getInstance();
        int temp=0;
        int tempCount=0;
        int tempType=0;
        String tempBeginTime="";
        String tempLastTime="";
        String TempCon="无";
        if(list!=null){
            //页面内容急躁次数的时间
            ArrayList<String> beginTime=new ArrayList<String>();
            ArrayList<String> lastTime=new ArrayList<String>();
            for (int i = 0; i < list.size(); i++) {
                if(i+1>list.size()-1){
                    break;
                }
                //急躁次数
                sumAbnormal += list.get(i).getCounttype().intValue();
                SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
                //获取两次急躁发生的时间
                Date date1 =sdf.parse(list.get(i).getSubtime());
                Date date2 =sdf.parse(list.get(i+1).getSubtime());
                Calendar calendar1 = Calendar.getInstance();
                Calendar calendar2 = Calendar.getInstance();
                calendar1.setTime(date1);
                calendar2.setTime(date2);
                lastDate1 = calendar1;
                lastDate2 = calendar2;
                lastDate1.add(Calendar.DATE, 1);
                //时间转换为秒 做对比
                long time =lastDate1.getTime().getTime();
                long time2 =lastDate2.getTime().getTime();
                if(time==time2){
                    temp++;
                    tempType++;
                }else{
                    lastTime.add(list.get(i).getSubtime()); //连续出现异常的天数大于5天的结尾时间
                    tempType=0;
                    temp=0;
                }if(temp==4 && tempType==4){    //连续出现异常的天数大于5天
                    temp=0;
                    tempCount++;
                    beginTime.add(list.get(i-3).getSubtime());//连续出现异常的天数大于5天的开始时间
                }
            }
            for(Object obj:beginTime)  {
                tempBeginTime+=obj+"到";  ;
            }
            for(Object obj:lastTime)  {
                tempLastTime+=obj+"。";
            }
            if(!"".equals(tempBeginTime)){
                String[] ary1 = tempBeginTime.split("到");
                String[] ary2 = tempLastTime.split("。");
                for (int i = 0; i < ary1.length; i++) {
                    TempCon+=ary1[i]+"至"+ary2[i]+"。";
                }
            }
        }
        String tempPercentage=String.format("%.2f", ((double)sumAbnormal/365)*100);
        DriverCommentParamsVo paramsVo = new DriverCommentParamsVo();
        paramsVo.setCorpId(user.getCorpId());
        paramsVo.setCompareValue(vo.getScore());
        paramsVo.setLineId(vo.getLineId());
        //lv 标语
        String lv = driverCommentService.getCommentGrade4Mood(paramsVo);
        paramsVo.setBeginTime(moodOccurTime);
        paramsVo.setOrganName(vo.getOrganName());
        paramsVo.setLineName(vo.getLineName());
        paramsVo.setDrvName(vo.getDrvName());
        paramsVo.setLineId(vo.getLineId());
        BigDecimal moodPercent = new BigDecimal(tempPercentage);
        paramsVo.setMoodPercent(moodPercent);
        //急躁次数
        paramsVo.setMoodOccurCount(tempCount);
        paramsVo.setMoodOccurTime(TempCon);
        //内容
        String content =  driverCommentService.getCommentContent4Mood(paramsVo);
        List<Object> list2 = new ArrayList<Object>();
        list2.add(list);
        list2.add(lv);
        list2.add(content);
        list2.add(tempCount);
        list2.add(tempPercentage);
        return this.getReturnResult(list2);
    }
}
